<template>
  <a-modal 
    :open="open" 
    title="UseTable Columns 格式" 
    width="1000px" 
    :footer="null" 
    @cancel="handleCancel" 
    :maskClosable="false"
  >
    <div class="extracted-data-container">
      <div style="margin-bottom: 16px;">
        <a-radio-group v-model:value="mode" @change="fetchColumnsCode">
          <a-radio-button value="vben">VBEN格式</a-radio-button>
          <a-radio-button value="longnows">LONGNOWS格式</a-radio-button>
        </a-radio-group>
      </div>
      <a-spin :spinning="loading">
        <codemirror
          v-model="generatedCode"
          :style="{ height: '400px' }"
          :autofocus="true"
          :indent-with-tab="true"
          :tab-size="2"
          :extensions="extensions"
        />
      </a-spin>

      <div class="copy-button-container">
        <a-button type="primary" @click="copyToClipboard" :loading="copying" :disabled="loading">
          {{ copying ? '复制中...' : '复制到剪贴板' }}
        </a-button>
        <span v-if="copySuccess" class="copy-success">复制成功!</span>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, watch } from 'vue'
import { config } from '../config'
import { Codemirror } from 'vue-codemirror'
import { javascript } from '@codemirror/lang-javascript'


const extensions = [javascript()]

const props = defineProps({
  open: {
    type: Boolean,
    required: true
  },
  data: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:open'])

const copying = ref(false)
const copySuccess = ref(false)
const loading = ref(false)
const generatedCode = ref('')
const mode = ref('longnows')

const fetchColumnsCode = async () => {
  if (props.data.length === 0) {
    generatedCode.value = '[]'
    return
  }

  loading.value = true
  try {
    const response = await fetch(`${config.domain}/api/generate-table-columns`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ data: props.data, mode: mode.value })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    generatedCode.value = result.code
  } catch (error) {
    console.error('获取表格Columns失败:', error)
    generatedCode.value = '// 获取表格Columns失败'
  } finally {
    loading.value = false
  }
}

watch(() => [props.open, props.data], ([newOpen]) => {
  if (newOpen) {
    fetchColumnsCode()
  }
}, { immediate: true })

const handleCancel = () => {
  emit('update:open', false)
}

const copyToClipboard = async () => {
  copying.value = true
  copySuccess.value = false

  try {
    // 检查浏览器是否支持Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(generatedCode.value)
      copySuccess.value = true
    } else {
      // 降级处理：使用传统的execCommand('copy')方法
      const textArea = document.createElement('textarea')
      textArea.value = generatedCode.value
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()

      const successful = document.execCommand('copy')
      document.body.removeChild(textArea)

      if (successful) {
        copySuccess.value = true
      } else {
        throw new Error('execCommand failed')
      }
    }

    // 3秒后隐藏成功提示
    setTimeout(() => {
      copySuccess.value = false
    }, 3000)
  } catch (err) {
    console.error('复制失败:', err)
    alert('复制失败，请手动复制')
  } finally {
    copying.value = false
  }
}
</script>

<style scoped>
.extracted-data-container {
  overflow-y: auto;
  padding: 15px;
}

.copy-button-container {
  margin-top: 16px;
  text-align: center;
  position: relative;
}

.copy-success {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  color: #52c41a;
  font-weight: bold;
  animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {
  0%,
  100% {
    opacity: 0;
  }

  20%,
  80% {
    opacity: 1;
  }
}
</style>